package com.yuanchuang.yp.mall.web.admin.common.config.shiro;

import com.alibaba.fastjson.JSONObject;
import com.yuanchuang.yp.mall.web.admin.common.utils.AesEncodeUtil;
import com.yuanchuang.yp.mall.web.admin.user.mapper.AuthPowerMapper;
import com.yuanchuang.yp.mall.web.admin.user.mapper.AuthRoleMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

/**
 * class_name: ShiroRealm
 * package: com.yuanchuang.yp.mall.web.admin.common.config.shiro
 * describe: TODO
 * @author: yuanyaun
 * creat_date: 2019/7/16
 * creat_time: 15:29
 **/
@Slf4j
public class ShiroRealm extends AuthorizingRealm {

    @Resource
    AuthRoleMapper authRoleMapper;
    @Resource
    AuthPowerMapper authPowerMapper;
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    /**
     * 授权
     * @param principal
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        return authorizationInfo;
    }

    /**
     * 认证
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        JwtToken jwtToken=(JwtToken) token;
        String tocken = String.valueOf(jwtToken.getPrincipal()) ;
        String jwtString="";
        try {
            jwtString = URLDecoder.decode(tocken, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            log.error("doGetAuthenticationInfo UnsupportedEncodingException"+tocken,e);
        }
        String userInfo = AesEncodeUtil.decrypt(jwtString);
        Integer userId = JSONObject.parseObject(userInfo).getInteger("id");
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(userId,tocken, getName());
        return authenticationInfo;
    }

}
